package com.usian.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.pojo.Employee;
import com.usian.pojo.Result;
import com.usian.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;



import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    public EmployeeService employeeService;

    @PostMapping("/login")
    public Result login(@RequestBody Employee employee, HttpSession session) {
        Result<Employee> result = employeeService.login(employee);
        if (result.getCode() == 1) {
            session.setAttribute("employee", result.getData().getId());
        }
        return result;
    }
    @PostMapping("/logout")
    public Result logout(HttpSession session){
        session.invalidate();
        return Result.success("退出登录");
    }

    @PostMapping
    public Result save(@RequestBody Employee employee,HttpSession session){
        Long empId= (Long) session.getAttribute("employee");
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);
        employeeService.save(employee);
        return Result.success("添加成功");
    }

    @GetMapping("page")
    public Result page(@RequestParam(defaultValue = "1")Integer page,@RequestParam(defaultValue = "3")Integer pageSize,String name){
        Page<Employee> employee=employeeService.page(page,pageSize,name);
        return Result.success(employee);
    }

    @PutMapping
    public Result updateEmp(@RequestBody Employee employee,HttpSession session){
        Long empId= (Long) session.getAttribute("employee");
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(empId);
        employeeService.updateEmp(employee);
        return Result.success("修改成功");

    }

    @GetMapping("{id}")
    public Result findById(@PathVariable Long id){
        Employee employee=employeeService.findById(id);
        return  Result.success(employee);
    }
}
